<template>
    <div>
        <el-dialog v-model="props.addSubordinateDialog" title="添加生产工单" width="70%" @close="handleClose" class="dialogs"
            @open="hanleOpenDialogAdd">
            <el-form :model="Addvalue" ref="formAdd" :rules="rulesAdd" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="工单编码" prop="workorderCode">
                            <el-input v-model="Addvalue.workorderCode" placeholder="请输入工单编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-switch v-model="isSwitch" active-value="自动生成" @change="switchCode">
                        </el-switch>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工单名称" prop="workorderName">
                            <el-input v-model="Addvalue.workorderName" placeholder="请输入工单名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="来源类型" prop="orderSource">
                            <el-radio-group v-model="Addvalue.orderSource">
                                <el-radio value="ORDER">客户类型</el-radio>
                                <el-radio value="STORE">库存备货</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="订单编码" v-if="Addvalue.orderSource === 'ORDER'">
                            <el-input v-model="Addvalue.sourceCode" placeholder="请输入订单编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单据状态">
                            <el-select v-model="Addvalue.status" placeholder="请选择单据状态" disabled>
                                <el-option v-for="item in DJstatus" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="工单类型" prop="workorderType">
                            <el-select v-model="Addvalue.workorderType">
                                <el-option v-for="item in GDworkorderType" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品编码" prop="productCode">
                            <el-input v-model="Addvalue.productCode" placeholder="请选择产品" clearable>
                                <template #append>
                                    <el-button :icon="Search" @click="showDialogPro"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品名称" prop="productName">
                            <el-input v-model="Addvalue.productName" placeholder="请选择产品" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="规格型号">
                            <el-input v-model="Addvalue.productSpc" placeholder="请选择产品" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单位">
                            <el-input v-model="Addvalue.unitOfMeasure" placeholder="请选择产品" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="工单数量" prop="quantity">
                            <el-input-number v-model="Addvalue.quantity" :min="1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="需求日期" prop="requestDate">
                            <el-date-picker v-model="Addvalue.requestDate" type="date" placeholder="请选择需求日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="批次号">
                            <el-input v-model="Addvalue.batchCode" placeholder="请输入批次号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="客户编码" v-if="Addvalue.orderSource === 'ORDER'">
                            <el-input v-model="Addvalue.clientCode" placeholder="请选择客户">
                                <template #append>
                                    <el-button :icon="Search" @click="showDialogCustomer" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户名称" v-if="Addvalue.orderSource === 'ORDER'">
                            <el-input v-model="Addvalue.clientName" placeholder="请选择客户" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="供应商编码"
                            v-if="Addvalue.workorderType === 'OUTSOURCE' || Addvalue.workorderType === 'PURCHASE'">
                            <el-input v-model="Addvalue.supplierCode" placeholder="请选择供应商">
                                <template #append>
                                    <el-button :icon="Search" @click="" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商名称"
                            v-if="Addvalue.workorderType === 'OUTSOURCE' || Addvalue.workorderType === 'PURCHASE'">
                            <el-input v-model="Addvalue.supplierName" placeholder="请选择供应商" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="Addvalue.remark" type="textarea" :rows="2" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit(formAdd)">保存</el-button>
                    <el-button @click="Visible">取消</el-button>
                </div>
            </template>

        </el-dialog>

        <!-- 产品/物料选择弹窗 -->
        <ProSelectionDialog :ProDialog="dialogVisiblePro" @close-dialog="colseDialog" @rowDataP="rowDataP" />

        <!-- 客户选择弹窗 -->
        <CustomerSelectionDialog :CustomerDialog="dialogVisibleCustomer" @close-dialog="colseDialog"
            @rowDataA="rowData" />

    </div>
</template>

<script setup>
import ProSelectionDialog from './ProSelectionDialog.vue';
import CustomerSelectionDialog from './CustomerSelectionDialog.vue';
import { Search, EditPen } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { nextTick, reactive, ref, onMounted } from 'vue';
import { insertProductionOrder } from '@/apis/lth/index';

const props = defineProps(['addSubordinateDialog', 'Addvalue']);
const emit = defineEmits(['close-dialog']);

const dialogVisiblePro = ref(false); //产品/物料选择弹窗
const dialogVisibleCustomer = ref(false); //客户选择弹窗

const DJstatus = ref([ //单据状态下拉
    { label: '草稿', value: 'PREPARE' },
    { label: '已确认', value: 'CONFIRMED' },
    { label: '已完成', value: 'APPROVED' }
]);
const GDworkorderType = ref([ //工单类型下拉
    { label: '自产', value: 'SELF' },
    { label: '外协', value: 'OUTSOURCE' },
    { label: '外购', value: 'PURCHASE' }
]);
const Addvalue = reactive({ //定义初始化数据属性
    workorderId: '',//工单id
    workorderCode: '',//工单编码
    workorderName: '',//工单名称
    orderSource: '',//来源类型
    sourceCode: '',// 单据来源（订单编码）
    workorderType: 'SELF',//工单类型
    productCode: '',//产品编码
    productName: '',//产品名称
    productSpc: '',//规格型号
    unitOfMeasure: '',//单位
    quantity: 0,//生产数量（订单数量）
    status: 'PREPARE',//单据状态，默认：草稿
    requestDate: '',//需求日期
    batchCode: '',//批次号
    parentId: '',//父级Id
    ancestors: '0',
    clientId: '',//客户Id
    clientCode: '',//客户编码
    clientName: '',//客户名称
    supplierCode: '',//供应商编码
    supplierName: '',//供应商名称
    remark: '',//备注
});

const formAdd = ref();
const resetFormAdd = reactive({ ...Addvalue });
const rulesAdd = {//验证规则对象
    workorderCode: [{
        required: true, //必填项
        message: "工单编码不能为空", //提示错误信息
        trigger: "blur"
    }],
    workorderName: [{
        required: true,
        message: "工单名称不能为空",
        trigger: "blur"
    }],
    orderSource: [{
        required: true,
        message: "来源类型不能为空",
        trigger: "blur"
    }],
    workorderType: [{
        required: true,
        message: "工单类型不能为空",
        trigger: "blur"
    }],
    productCode: [{
        required: true,
        message: "产品编码不能为空",
        trigger: "blur"
    }],
    productName: [{
        required: true,
        message: "产品名称不能为空",
        trigger: "blur"
    }],
    quantity: [{
        required: true,
        message: "生产数量不能为空",
        trigger: "blur"
    }],
    requestDate: [{
        required: true,
        message: "需求日期不能为空",
        trigger: "blur"
    }],
};

const hanleOpenDialogAdd = () => { //打开对话框的处理函数
    if (props.Addvalue) { // 如果 props.Addvalue 存在，则将其值合并到 Addvalue 中
        const allowedKeys = new Set(Object.keys(Addvalue));
        const filteredProps = Object.fromEntries(
            Object.entries(props.Addvalue).filter(([key]) => allowedKeys.has(key))
        );
        Object.assign(Addvalue, filteredProps);
    }
    nextTick(() => {
        formAdd.value.clearValidate(); //清空校验（清空表单校验结果，以便用户重新输入数据）
    })
};

const showDialogPro = () => { //Go产品\物料选择
    dialogVisiblePro.value = true;
};
const rowDataP = (row) => { //获取选中的产品/物料进行存储
    console.log("产品数据：", row);
    Addvalue.productId = row.materialNo;
    Addvalue.productCode = row.materialProductCode;
    Addvalue.productName = row.productName;
    Addvalue.productSpc = row.specificationAndModel;
    Addvalue.unitOfMeasure = row.unitName;
};
const showDialogCustomer = () => { //Go客户选择
    dialogVisibleCustomer.value = true;
};
const rowData = (row) => {
    console.log("客户数据：", row);
    Addvalue.clientId = row.customerId;
    Addvalue.clientCode = row.customerCode;
    Addvalue.clientName = row.customerName;
};

const onSubmit = async (value) => { //保存提交数据
    if (!value) return;
    await value.validate(valid => {
        if (valid) {
            const insertOrderValue = {// 创建一个新的对象来保存提交的数据
                workorderCode: Addvalue.workorderCode,
                workorderName: Addvalue.workorderName,
                orderSource: Addvalue.orderSource,
                sourceCode: Addvalue.sourceCode,
                status: Addvalue.status,
                workorderType: Addvalue.workorderType,
                productId: Addvalue.productId,
                productCode: Addvalue.productCode,
                productName: Addvalue.productName,
                productSpc: Addvalue.productSpc,
                unitOfMeasure: Addvalue.unitOfMeasure,
                quantity: Addvalue.quantity,
                requestDate: Addvalue.requestDate,
                batchCode: Addvalue.batchCode,
                ancestors: Addvalue.ancestors,
                clientId: Addvalue.clientId,
                clientCode: Addvalue.clientCode,
                clientName: Addvalue.clientName,
                supplierCode: Addvalue.supplierCode,
                supplierName: Addvalue.supplierName,
                remark: Addvalue.remark,
                parentId: Addvalue.workorderId, // 确保 parentId 不为空
            };// console.log("添加子工单数据：", insertOrderValue);
            insertProductionOrder(insertOrderValue).then(res => { //添加子工单
                Addvalue.workorderId = res
                ElMessage.success("新增成功");
                handleClose();
            }).catch(() => {
                console.log("新增失败");
            })
        } else { // ElMessage.error("请根据提示完整表单数据！");
            console.log("请根据提示完整表单数据！");
        }
    })
};

const handleClose = () => {//关闭自己
    Object.assign(Addvalue, resetFormAdd);//清空输入框搜索参数
    isSwitch.value = false;//关闭编码开关
    emit('close-dialog');
};

const Visible = () => {//取消自己事件
    emit('close-dialog');
};

const colseDialog = async () => {//关闭弹窗事件
    dialogVisibleCustomer.value = false;//关闭客户选择
    dialogVisiblePro.value = false;//关闭物料/产品选择
};

const isSwitch = ref(false);//生成编码开关更新状态
// const codeCounter = ref(0);//用于生成编码的计数器
const switchCode = (value) => {//生成编码开关
    const Code = createID();
    if (value) {
        Addvalue.workorderCode = Code;
    } else {
        Addvalue.workorderCode = '';
    }
};
function createID() {//工单编码生成
    let code = 'MO';
    let date = new Date();
    let year = date.getFullYear();
    let month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份补零
    let strDate = ('0' + date.getDate()).slice(-2); // 日期补零
    code = code + year + month + strDate + Math.floor(Math.random() * 10000);
    // code = code + year + month + strDate + ('0000' + (++codeCounter.value)).slice(-4); // 后面拼接递增的数字
    return code;
};

</script>

<style scoped></style>
